package com.wx.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.alibaba.fastjson.JSON;

public class ObjectUtil {

	/**
	 * 深度拷贝
	 *<pre> </pre>
	 * @param bean
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T deepClone(T bean){
		try {
			if(bean ==null ){
				return null;
			}
			return (T) JSON.parseObject(JSON.toJSONString(bean), bean.getClass()) ;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 深度拷贝
	 *<pre> </pre>
	 * @param bean
	 * @param clazz
	 * @return
	 */
	public static <T> T deepClone(Object bean, Class<T> clazz){
		try {
			if(bean ==null ){
				return null;
			}
			return JSON.parseObject(JSON.toJSONString(bean),clazz) ;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 文件转化为Object
	 * 
	 * @param fileName
	 * @return byte[]
	 */
	@SuppressWarnings("unchecked")
	public static <T> T file2Object(String fileName) {

		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = new FileInputStream(fileName);
			ois = new ObjectInputStream(fis);
			Object object = ois.readObject();
			return (T)object;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (ois != null) {
				try {
					ois.close();
				} catch (IOException e2) {
					e2.printStackTrace();
				}
			}
		}
		return null;
	}

	/**
	 * 把Object输出到文件
	 * 
	 * @param obj
	 * @param outputFile
	 */
	public static <T> void object2File(T obj, String outputFile) {
		ObjectOutputStream oos = null;
		FileOutputStream fos = null;
		try {
			File f = new File(outputFile);
			if (!f.exists()) {
				f.createNewFile();
			}
			fos = new FileOutputStream(f);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(obj);
			oos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (oos != null) {
				try {
					oos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e2) {
					e2.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) {

	}

}